<template>
  <el-form :model="form" label-width="auto" @keydown.enter.prevent="getData">
    <el-row :gutter="12">
      <el-col :span="8">
        <el-form-item label="短视频标题">
          <el-input
            v-model="form.title"
            placeholder="请输入短视频标题"
            @blur="nameBlur"
            clearable
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <div>
    <el-button type="primary" style="margin-right: 10px" @click="handleAddVideo"
      >新增短视频</el-button
    >
    <el-button type="danger" :disabled="selectIds.length === 0" @click="batchDelete"
      >批量删除</el-button
    >
    <!--    <el-button type="primary" @click="SyncVideo">-->
    <!--      <el-icon>-->
    <!--        <Refresh />-->
    <!--      </el-icon>-->
    <!--      同步默认短视频-->
    <!--    </el-button>-->
  </div>

  <art-table
    :data="tableData"
    :loading="tableLoading"
    :currentPage="pageNum"
    :pageSize="pageSize"
    :total="pageTotal"
    @current-change="currentChange"
    @size-change="sizeChange"
    @selection-change="handleSelectionChange"
  >
    <template #default>
      <el-table-column type="selection" width="55" />
      <el-table-column prop="sortOrder" label="排序" width="160" #default="scope">
        <span v-if="editRowSort !== scope.$index">{{ scope.row.sortOrder }}</span>
        <el-input
          v-else
          v-model="scope.row.sortOrder"
          maxlength="6"
          show-word-limit
          style="width: 110px"
          @keydown.enter="submitSort(scope.row)"
        />
        <i
          v-if="editRowSort !== scope.$index"
          class="iconfont-sys edit-icon"
          @click="editRowSort = editRowSort === scope.$index ? -1 : scope.$index"
          >&#xe65f;</i
        >
        <i v-else class="iconfont-sys edit-icon" @click="submitSort(scope.row)">&#xe616;</i>
      </el-table-column>
      <!-- 视频内容 -->
      <el-table-column label="视频标题" prop="title" width="400"></el-table-column>
      <el-table-column label="封面图" prop="coverUrl" width="300">
        <template #default="scope">
          <div>
            <el-image
              v-if="scope.row.coverUrl"
              :src="scope.row.coverUrl"
              class="tableimg"
              :preview-src-list="[scope.row.coverUrl]"
              :preview-teleported="true"
              fit="cover"
              :hide-on-click-modal="true"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="点赞" prop="likeCount" width="100" />
      <el-table-column label="评论" prop="commentCount" width="100" />
      <el-table-column label="收藏" prop="followCount" width="100" />
      <!-- 视频链接 -->
      <el-table-column #default="scope" prop="requireVip" label="用户权限">
        <!-- <el-switch v-model="scope.row.isPay" :active-value="1" :inactive-value="0" @change="editPay(scope.row)" /> -->
        <div style="display: flex; align-items: center">
          {{ scope.row.requireVip === 0 ? '全部用户可看' : '仅限VIP会员可看' }}
          <img
            src="https://image.lutongjiakao.com/system/5707eab8fee2418f89f4aecbf9466d5e.png"
            alt=""
            v-if="scope.row.requireVip === 1"
            class="vip_icon"
          />
        </div>
      </el-table-column>

      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="() => changeStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作时间" prop="updateTime">
        <template #default="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <button-table type="edit" @click="buttonMoreClick(scope.row)" />
          <button-table type="delete" @click="handleDel(scope.row.id)" />
        </template>
      </el-table-column>
    </template>
  </art-table>

  <add-video-dialog
    v-if="showAddVideoDialog"
    :show-add-video-visible="showAddVideoDialog"
    :group-info="editInfo"
    :edit-info="editData"
    @close-dialog="closeSelectionDialog"
  />

  <el-dialog
    v-model="videoDialogVisible"
    width="60%"
    :destroy-on-close="true"
    class="video-dialog"
    :close-on-click-modal="false"
  >
    <template #header>
      <h2>{{ previewTitle }}</h2>
    </template>

    <template #default>
      <video
        v-if="videoDialogVisible"
        :src="previewSrc"
        controls
        autoplay
        style="width: 100%; height: auto"
      />
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { getVideoPage, updateVideoSortOrStat, batchDelVideo } from '@/api/marketing'
  import AddVideoDialog from './AddVideoDialog.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'

  const props = defineProps<{
    editInfo: any
  }>()

  const editRowSort = ref(-1)

  watch(
    () => props.editInfo,
    () => {
      getData()
    }
  )

  const tableData = ref([])
  const pageNum = ref(1)
  const pageSize = ref(10)
  const pageTotal = ref(0)
  const tableLoading = ref(false)
  const selectIds = ref<string[]>([])
  const showAddVideoDialog = ref(false)
  const editData = ref({})

  const videoDialogVisible = ref(false)
  const previewSrc = ref('')
  const previewTitle = ref('')

  const form = reactive({
    title: ''
  })

  const currentChange = (val: number) => {
    pageNum.value = val
    getData()
  }
  const sizeChange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData()
  }

  function handleSelectionChange(data: any[]) {
    selectIds.value = data.map((item) => item.id)
  }

  function batchDelete() {
    ElMessageBox.confirm('确定删除吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let ids = selectIds.value.join(',')
      handleDelete(ids)
    })
  }

  function buttonMoreClick(item: any) {
    showAddVideoDialog.value = true
    editData.value = JSON.parse(JSON.stringify(item))
  }

  // const SyncVideo = async () => {
  //   const res = await getSyncVideo()
  //   if (res.code === '00000') {
  //     ElMessage.success('同步成功')
  //     emit('uploadGroup')
  //     getData()
  //   }
  // }

  function handleDel(id: string) {
    ElMessageBox.confirm('确定删除吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      handleDelete(id)
    })
  }

  async function handleDelete(ids: string) {
    try {
      const res = await batchDelVideo({
        ids
      })
      if (res.code === '00000') {
        await getData()
        selectIds.value = []
        ElMessage.success('删除成功')
      }
    } catch (e) {
    } finally {
    }
  }

  function handleAddVideo() {
    showAddVideoDialog.value = true
    editData.value = { id: '' }
  }

  function closeSelectionDialog(value: boolean) {
    showAddVideoDialog.value = false
    if (value) {
      getData()
    }
  }

  async function getData() {
    const obj: Record<string, any> = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      creatorId: props.editInfo.id
    }

    for (const key in form) {
      const typedKey = key as keyof typeof form
      if (form[typedKey] !== '') {
        obj[typedKey] = form[typedKey]
      }
    }

    try {
      tableLoading.value = true
      const res = await getVideoPage(obj)
      if (res.code === '00000') {
        tableData.value = res.data.list
        pageTotal.value = res.data.total
      }
    } catch (e) {
    } finally {
      tableLoading.value = false
    }
  }

  const nameBlur = (e: any) => {
    pageNum.value = 1
    pageSize.value = 10
    getData()
  }

  async function submitSort(row: any) {
    const res = await updateVideoSortOrStat(row.id, {
      sortOrder: row.sortOrder
    })
    if (res.code === '00000') {
      ElMessage.success('修改成功')
      editRowSort.value = -1
      await getData()
    }
  }

  async function changeStatus(row: any) {
    const res = await updateVideoSortOrStat(row.id, {
      status: row.status
    })
    if (res.code === '00000') {
      ElMessage.success('修改成功')
      editRowSort.value = -1
      await getData()
    }
  }
</script>

<style scoped lang="scss">
  .tableimg {
    width: 80px;
    height: 80px;
  }

  .vip_icon {
    width: 15px;
    height: 15px;
    margin-left: 5px;
  }

  .edit-icon {
    margin-left: 4px;
    cursor: pointer;
    color: var(--el-color-primary);
  }
</style>
